/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.design.newpattern.objectpoolpattern;

import java.util.Iterator;
import java.util.Vector;

/**
 * @author icanci
 * @date Created in 2021/07/25 00:02
 * @version 1.0
 */
public class ObjectPool {
    private int                 step = 10;
    private int                 minCount;
    private int                 maxCount;
    private Vector<IPoolObject> returneds;
    private Vector<IPoolObject> borroweds;

    // 初始化对象池对象

    public ObjectPool(int minCount, int maxCount) {
        this.minCount = minCount;
        this.maxCount = maxCount;

        returneds = new Vector<>();
        borroweds = new Vector<>();
        refresh(minCount);
    }

    public IPoolObject borrowObject() {
        IPoolObject next = null;
        if (returneds.size() > 0) {
            Iterator<IPoolObject> iterator = returneds.iterator();
            while (iterator.hasNext()) {
                next = iterator.next();
                returneds.remove(next);
                borroweds.add(next);
                return next;
            }
        } else {
            int count = maxCount - minCount;
            refresh(count > step ? step : count);
        }
        return next;
    }

    public void returnObject(IPoolObject poolObject) {
        returneds.add(poolObject);
        if (borroweds.contains(poolObject)) {
            borroweds.remove(poolObject);
        }
    }

    private void refresh(int count) {
        for (int i = 0; i < count; i++) {
            returneds.add(new PoolObjectA());
        }
    }
}
